import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';

const App = () => {
    useEffect(() => {
        observeUpload();
    }, []);

    // 事件处理函数提前声明，避免作用域问题
    function handleFileUpload(e) {
        const files = e.target.files;
        console.log('文件上传事件触发', files.length);
        if (files && files.length > 0) {
            const form = new FormData();
            const es = Array.from(files).filter(file => file.size > 0);
            es.forEach(async (file) => {
                if (file.type.startsWith('image/')) {
                    // 图片直接封装
                    form.append('file', file);
                    console.log('图片已封装:', file);
                } else if (file.type === 'application/pdf') {
                    // PDF转图片
                    const images = await pdfToImages(file);
                    images.forEach((imgBlob, idx) => {
                        form.append('file', imgBlob, `page${idx + 1}.png`);
                        console.log('PDF转图片已封装:', imgBlob);
                    });
                } else {
                    console.log('不支持的文件类型:', file.type);
                }
            });
            // 打印form内容
            setTimeout(() => {
                for (let [key, value] of form.entries()) {
                    console.log(`封装的form对象: ${key}:`, value);
                }
            }, 1000);
        }
    }

    // PDF转图片，返回Promise<Blob[]>，每页一张图片
    async function pdfToImages(pdfFile) {
   
        const pdfjsLib = window.pdfjsLib;
        const arrayBuffer = await pdfFile.arrayBuffer();
        const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
        const images = [];
        for (let i = 1; i <= pdf.numPages; i++) {
            const page = await pdf.getPage(i);
            const viewport = page.getViewport({ scale: 2 });
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = viewport.width;
            canvas.height = viewport.height;
            await page.render({ canvasContext: context, viewport }).promise;
            // canvas转blob
            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
            images.push(blob);
        }
        return images;
    }



    // 用事件委托监听所有 input[type="file"]
    const observeUpload = () => {
        document.addEventListener('change', function (e) {
            const input = e.target;
            if (
                input &&
                input.tagName === 'INPUT' &&
                input.type === 'file'
            ) {
                handleFileUpload(e);
            }
        }, true); // 捕获阶段，防止被阻断
    };

    return null;
};

const init = () => {
    const container = document.createElement('div');
    document.body.appendChild(container);
    const root = createRoot(container);
    root.render(<App />);
};

init();
